//
//  FlyActionSheet.m
//  BYActionsheet
//
//  Created by lifayu on 2017/9/5.
//  Copyright © 2017年 Bangyang. All rights reserved.
//

#import "FlyActionSheet.h"

#define kFlyCellHeight  44
#define KFlySeparatorHeight 6
#define KFlyTableHeaderFooterHeight 15

#define KFlyTableViewMaxHeight ScreenHeight - KFlyTableHeaderFooterHeight*2 - 20

@interface FlyActionSheet()

@property (strong, nonatomic) UIView *backgroundView;

@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) NSArray *contents;

@property (nonatomic,copy) void (^completionHandler)(NSInteger selectIndex);

@end

@implementation FlyActionSheet

- (UIView *)initWithContents:(NSArray *)contents
{
    self = [super init];
    if(self)
    {
        self.backgroundColor = [UIColor clearColor];
        self.contents = contents;
        self.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        [self addBackgroundView];
        [self addTableView];
    }
    return self;
}

- (void)addBackgroundView
{
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    backgroundView.backgroundColor = UIColorFromRGBA(0x000000, 0.4);
    [self addSubview:backgroundView];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    [backgroundView addGestureRecognizer:tap];
    self.backgroundView.alpha = 0;
    self.backgroundView = backgroundView;
}

- (void)addTableView
{
    if(self.contents.count <= 0)
    {
        return;
    }
    CGFloat cellHeight = kFlyCellHeight*self.contents.count;
    CGFloat separatorHeight = KFlySeparatorHeight*(self.contents.count - 1);
    CGFloat tableViewHeight = cellHeight + separatorHeight;
    if(tableViewHeight > KFlyTableViewMaxHeight)
    {
        tableViewHeight = KFlyTableViewMaxHeight;
    }
     UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(15, ScreenHeight, ScreenWidth - 30, tableViewHeight) style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor clearColor];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = kFlyCellHeight;
    tableView.bounces = NO;
    tableView.showsHorizontalScrollIndicator = NO;
    tableView.showsVerticalScrollIndicator = NO;
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
    [self addSubview:tableView];
    self.tableView = tableView;
}

#pragma mark - tapClick
- (void)tapClick:(UITapGestureRecognizer *)tap
{
    [self hidden:-1];
}
#pragma mark - show/hidden
- (void)showInView:(UIView *)view completionHandler:(void (^)(NSInteger selectIndex))completionHandler
{
    if(self.contents.count <= 0)
    {
        return;
    }
    self.completionHandler = completionHandler;
    UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
    if (keyWindow == nil)
    {
        [view addSubview:self];
    }
    else
    {
        [keyWindow addSubview:self];
    }
    [UIView animateWithDuration:.28 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        
        self.backgroundView.alpha = 1;
        self.tableView.frame = CGRectMake(15, 20 + KFlyTableHeaderFooterHeight + KFlyTableViewMaxHeight - self.tableView.height, ScreenWidth - 30, self.tableView.height);
    } completion:^(BOOL finished) {

    }];
}

- (void)hidden:(NSInteger)index
{
    if(index >= 0 && index < self.contents.count)
    {
        if(self.completionHandler)
        {
            self.completionHandler(index);
        }
    }
    [UIView animateWithDuration:.28 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.tableView.frame = CGRectMake(15, ScreenHeight, ScreenWidth - 30, self.tableView.height);
        self.backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.tableView removeFromSuperview];
        [self.backgroundView removeFromSuperview];
        [self removeFromSuperview];
    }];
}


#pragma mark - UITableViewDataSource && UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.contents.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id object = [self.contents objectAtIndex:indexPath.section];
    if([object isKindOfClass:[UIView class]])
    {
        UITableViewCell * cell = [[UITableViewCell alloc] init];
        cell.backgroundColor = kWhiteColor;
        cell.cornerRadius = 8;
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        UIView *customView = (UIView *)object;
        customView.frame = CGRectMake(0, 0, ScreenWidth - 30, kFlyCellHeight);
        [cell.contentView addSubview:customView];
        customView.userInteractionEnabled = NO;
        return cell;
    }
    else if ([object isKindOfClass:[NSString class]])
    {
        static NSString * identfier = @"cellIdentfier";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identfier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identfier];
            cell.backgroundColor = kWhiteColor;
            cell.cornerRadius = 8;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.font = [UIFont systemFontOfSize:18.0];
            
            if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsZero];
            }
            
            if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                [cell setLayoutMargins:UIEdgeInsetsZero];
            }
        }
        NSString *title = (NSString *)object;
        cell.textLabel.text = title;
        
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kFlyCellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section == self.contents.count - 1)
    {
        return 0.0001f;
    }
    return KFlySeparatorHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self hidden:indexPath.section];
}


@end
